using fCloud.SensorApi.Models;
using Microsoft.EntityFrameworkCore;

namespace fCloud.SensorApi.Services;

public class MysqlDbService(SensorDbContext dbContext):IMysqlDbService
{
    public async Task<List<Sensor>> GetSensors()
    {
        return await dbContext.Sensors.ToListAsync();
    }

    public async Task<List<AlarmData>> GetAlarmData()
    {
        return await dbContext.AlarmDateSet.ToListAsync();
    }

    public async Task<List<Device>> GetDevices()
    {
        return await dbContext.Devices
            .Select(d => new Device
            {
                Id = d.Id,
                Name = d.Name,
                TName = d.TName,
                Location = d.Location,
                Status = d.Status,
                Type = d.Type,
            })
            .ToListAsync();
    }

    public async Task<List<SensorData>> GetSensorData()
    {
        return await dbContext.SensorDataSet.ToListAsync();
    }

    public async Task InsertSensorData(SensorData sensorData)
    {
        await dbContext.SensorDataSet.AddAsync(sensorData);
    }
    // ✅ 分页查询实现
    public async Task<List<SensorData>> GetSensorDataBySensorSnAsync(
        string sensorSn,
        int page,
        int pageSize)
    {
        return await dbContext.SensorDataSet
            .Where(s => s.SensorSn == sensorSn)
            .OrderByDescending(s => s.CreateTime)
            .Skip((page - 1) * pageSize)
            .Take(pageSize)
            .ToListAsync();
    }

    // ✅ 获取总数实现
    public async Task<int> CountSensorDataBySensorSnAsync(string sensorSn)
    {
        return await dbContext.SensorDataSet
            .CountAsync(s => s.SensorSn == sensorSn);
    }
}

public interface IMysqlDbService
{
    public  Task<List<Sensor>> GetSensors();
    public  Task<List<AlarmData>> GetAlarmData();
    public  Task<List<Device>> GetDevices();
    public  Task<List<SensorData>> GetSensorData();
    public Task InsertSensorData(SensorData sensorData);

    public  Task<List<SensorData>> GetSensorDataBySensorSnAsync(
        string sensorSn,
        int page,
        int pageSize);

    public Task<int> CountSensorDataBySensorSnAsync(string sensorSn);
}